package cn.bytets.speed.consumer;

import cn.bytest.netty.protocol.NettyProtocol;
import cn.bytets.rpc.api.close.RpcCloseHook;
import cn.bytets.rpc.api.protocol.Protocol;
import cn.bytets.rpc.api.proxy.ProxyFactory;
import cn.bytets.rpc.api.proxy.impl.JavassistProxyFactory;
import cn.bytets.rpc.common.URL;

import java.sql.Array;
import java.util.ArrayList;
import java.util.List;

public class ReferenceConfig<T>{

    private RegistryConfig registryConfig;

    private Class<?> interfaceClass;

    private String interfaceName;
    /**
     * 这里可以使用SPI方式获取
     */
    private ProxyFactory factory = new JavassistProxyFactory();
    /**
     * 这里可以使用SPI方式获取
     */
    private Protocol protocol = new NettyProtocol();

    private boolean init = false;

    private T ref;

    public T get(){
        if (!init){
            initConfig();
            Runtime.getRuntime().addShutdownHook(new RpcCloseHook());
        }
        return ref;
    }
    public synchronized void initConfig(){
        if (null!=ref){
            return;
        }
        //这里应用从注册中心获取
        URL url = getUrls().get(0);
        this.ref = (T)factory.getProxy(protocol.refer(this.interfaceClass, url), this.interfaceClass);
    }
    public List<URL> getUrls(){
        ArrayList<URL> list = new ArrayList<>();
        list.add(new URL("netty","127.0.0.1",8080));
        return list;
    }

    public void setRegistry(RegistryConfig registryConfig){
        this.registryConfig = registryConfig;
    }

    public void setInterface(Class<?> interfaceClass){
        this.interfaceClass = interfaceClass;
        this.interfaceName = interfaceClass.getName();
    }
}
